/**
 * 传入后端数据,返回站点数据
 * @param {Array} upRoute [上行原始数据]
 * @param {Array} downRoute [下行原始数据]
 */
export const initRouteData = (stationList, containerWidth, containerHeight) => {
  const upArr = []
  const downArr = []
  let leftRightPadding = 25;
  let defaultPostition_y = (containerHeight / 2) - 60
  let uptPostition_y = defaultPostition_y
  let downtPostition_y = defaultPostition_y + 100
  //算出上下行站点的并集
  let maxLength = stationList.length;
  let spacePx = (containerWidth - leftRightPadding * 2 - 12) / (maxLength - 1);
  let sourceMarkerPosition = leftRightPadding
  stationList.forEach((stationInfos, i) => {
    let upExist = Object.keys(stationInfos.upSite).length > 0;
    let downExist = Object.keys(stationInfos.downSite).length > 0;
    if (upExist) {
      let upItem = stationInfos.upSite;
      upItem.stationNameFull = upItem.stationName;
      upItem.stationName = upItem.stationName.substring(0, 4);
      upArr.push({
        id: upItem.stationId + '-' + upItem.direction + '-' + upItem.stationOrder,
        x: sourceMarkerPosition,
        y: uptPostition_y,
        shape: 'up-big-custom-circle',
        attrs: {
          label: {
            x: 10,
            y: 40,
            text: upItem.stationName,
          },
        },
        data: {
          ...upItem
        },
      })
    }
    let downItem = stationInfos.downSite;
    if (downExist) {
      downItem.stationNameFull = downItem.stationName;
      downItem.stationName = downItem.stationName.substring(0, 4);
    }
    if (upExist && downExist) {
      downArr.push({
        id: downItem.stationId + '-' + downItem.direction + '-' + downItem.stationOrder,
        x: sourceMarkerPosition,
        y: downtPostition_y,
        shape: 'down-big-custom-circle',
        data: {
          ...downItem
        },
      })
    }
    if (!upExist && downExist) {
      downArr.push({
        id: downItem.stationId + '-' + downItem.direction + '-' + downItem.stationOrder,
        x: sourceMarkerPosition,
        y: downtPostition_y,
        shape: 'down-big-custom-circle',
        attrs: {
          label: {
            x: 10,
            y: -40,
            text: downItem.stationName,
          },
        },
        data: {
          ...downItem
        },
      })
    }
    sourceMarkerPosition += spacePx
  })

  return {
    upArr,
    downArr
  }
}
/**
 * 传入上下行站点数据,返回上下行站点间连线
 * @param {Array} upRoute [上行站点数据]
 * @param {Array} downRoute [下行站点数据]
 */
export const initEdgeData = (upRoute, downRoute) => {
  // 线比站点少一
  const upLineArr = upRoute.slice(0, upRoute.length - 1).map((item, index) => {
    const nextItem = upRoute[index + 1]
    return {
      id: 'edge-' + nextItem.id,
      shape: 'edge',
      source: item.id,
      target: nextItem.id,
      markup: [{
          tagName: 'path',
          selector: 'stroke',
        },
        {
          tagName: 'path',
          selector: 'fill',
        },
      ],
      connector: {
        name: 'rounded'
      },
      attrs: {
        fill: {
          connection: true,
          fill: 'none',
        },
        stroke: {
          fill: 'none',
          stroke: '#4BD17A',
          strokeWidth: 4,
          connection: true,
          strokeLinecap: 'round',
        },
      },
      data: {
        name: item.name
      }
    }
  })

  const downLineArr = downRoute.slice(0, downRoute.length - 1).map((item, index) => {
    const nextItem = downRoute[index + 1]
    return {
      id: 'edge-' + nextItem.id,
      shape: 'edge',
      source: item.id,
      target: nextItem.id,
      markup: [{
          tagName: 'path',
          selector: 'stroke',
        },
        {
          tagName: 'path',
          selector: 'fill',
        },
      ],
      connector: {
        name: 'rounded'
      },
      attrs: {
        fill: {
          connection: true,
          fill: 'none',
        },
        stroke: {
          fill: 'none',
          stroke: '#668FF5',
          strokeWidth: 4,
          connection: true,
          strokeLinecap: 'round',
        },
      },
      data: {
        name: item.name
      }
    }
  })

  return {
    upLineArr,
    downLineArr
  }
}

/**
 * 传入单线路数据,返回环线站点及环线站点线路数据,线路内有标识是否为中间转折线(环线用)
 * @param {Array} Route [线路原始数据]
 * */
export const initLoopLineNode = (Route, containerWidth, containerHeight) => {
  let loopLineNode = []
  let loopLineEdge = []
  let loopLineNodePostion_x = 0
  let loopLineNodePostion_y = 40
  let middleIndex = 0
  let avg = (Route.length) / 2;
  let middleNum = Math.ceil(avg);

  let Xmiddle = middleNum; //middleNum == avg ? middleNum : avg +1 ; //0 
  //环线一半站点的间隔计算
  let leftRightPadding = 25;
  let minFlag = Route.length <= 10;
  let spaceWith = minFlag ? (containerWidth - leftRightPadding * 2 - 12) / (Route.length - 1) : (containerWidth - leftRightPadding * 2 - 20 - 12) / Xmiddle
  loopLineNodePostion_x += leftRightPadding;
  Route.forEach((stationInfos, index) => {
    let item = stationInfos.upSite;
    item.stationNameFull = item.stationName;
    item.stationName = item.stationName.substring(0, 4);
    if (minFlag) {
      loopLineNode.push({
        id: item.stationId + '-' + item.direction + '-' + item.stationOrder,
        x: loopLineNodePostion_x,
        y: 40,
        shape: 'up-big-custom-circle',
        attrs: {
          label: {
            x: 10,
            y: 40,
            text: item.stationName,
          },
        },
        data: {
          ...item
        },
      })
      loopLineNodePostion_x += spaceWith
    } else {
      if (index < Xmiddle) {
        loopLineNodePostion_y = 40
        loopLineNodePostion_x += spaceWith
        middleIndex = index
      } else {
        loopLineNodePostion_x = loopLineNode[middleIndex--].x - (spaceWith / 2)
        loopLineNodePostion_y = 140
      }
    }

    loopLineNode.push({
      id: item.stationId + '-' + item.direction + '-' + item.stationOrder,
      x: loopLineNodePostion_x,
      y: loopLineNodePostion_y,
      shape: 'up-big-custom-circle',
      attrs: {
        label: {
          x: 10,
          y: loopLineNodePostion_y == 40 ? 50 : -60,
          text: item.stationName,
          color: '#000'
        },
      },
      data: {
        middleNum,
        ...item
      },
    })
  })

  let isMiddleLine = false
  let vertices = []

  for (let i = 0; i < loopLineNode.length; i++) {
    let item = loopLineNode[i]
    let nextItem = loopLineNode[i + 1]

    // if (i == Xmiddle) {
    //   isMiddleLine = true
    //   vertices = [
    //     { x: item.x + 100, y: 30 },
    //     { x: item.x + 100, y: 210 }
    //   ]
    // }

    if (i == loopLineNode.length - 1) break
    let edgeOption = {
      shape: 'edge',
      source: item.id,
      target: nextItem.id,
      markup: [{
          tagName: 'path',
          selector: 'stroke',
        },
        {
          tagName: 'path',
          selector: 'fill',
        },
      ],
      connector: {
        name: 'rounded'
      },
      vertices,
      attrs: {
        fill: {
          connection: true,
          fill: 'none',
        },
        stroke: {
          fill: 'none',
          stroke: '#4BD17A',
          strokeWidth: 4,
          connection: true,
          strokeLinecap: 'round',
        },
      },
      data: {
        name: item.name,
        isMiddleLine: vertices.length ? true : false
      }
    };
    if (i == Xmiddle - 1) {
      edgeOption.router = {
        name: 'oneSide',
        args: {
          side: 'right',
          padding: 20,
        },
      }
    }
    loopLineEdge.push(edgeOption)

    vertices = []
  }
  // loopLineEdge = []
  return {
    loopLineNode,
    loopLineEdge
  }
}

/**
 * 传入车辆+上行站点+下行站点，返回车辆所在位置Node数据
 * @param {Array} vehicleList [当前线路车辆信息]
 * @param {Array} upRouteNode [上行线路]
 * @param {Array} downRouteNode [下行线路]
 * @param {Array} isPlateNo [是否车牌号]
 * @param {Array} isSmall [是否小图标]
 * @param {Array} isLine [是否基础标准直线图]
 * @param {Array} isLoop [是否为环线]
 * */
export const initCarNode = (vehicleList, upRouteNode, downRouteNode = [], isPlateNo, isSmall, isLine, isLoop = false) => {
  const vehicleNode = []
  // console.log('车辆信息', vehicleList)
  // console.log('isSmall', isSmall)
  vehicleList.forEach((item) => {
    const routeId = item.stationId + '-' + item.direction + '-' + item.stationOrder
    let Xmiddle = 0;
    if (isLoop) {
      let avg = (upRouteNode.length) / 2;
      Xmiddle = Math.ceil(avg);
    }

    // 上线车辆
    if (item.direction == 1) {
      upRouteNode.forEach((ele, index) => {
        if (routeId == ele.id) {
          let x, y, smallOffestX;
          smallOffestX = !isSmall ? 20 : 0;
          if (isLoop) {
            if (item.stationOrder < Xmiddle) {
              y = ele.y - 30
            }else if (item.stationOrder == Xmiddle) {
              if (item.onStation == true) {
                y = ele.y - 30
              } else {
                y = upRouteNode[index + 1].y + 20
                item.direction = 2;
              }
            } else {
              y = ele.y + 20
              item.direction = 2;
            }
            if (item.onStation == true) {
              x = ele.x - smallOffestX
            } else if (item.onStation == false && item.stationOrder != item.endStationOrder) {
              if (item.direction == 1) {
                //计算左到右
                x = ele.x + (upRouteNode[index + 1].x - ele.x) / 2 - smallOffestX
              } else {
                //计算右到左
                x = ele.x - (ele.x - upRouteNode[index + 1].x) / 2 - smallOffestX
                if (item.stationOrder == Xmiddle) {
                  x = x + 20
                }
              }
            }
          } else {
            y = ele.y - 30
            if (item.onStation == true) {
              x = ele.x - smallOffestX
            } else {
              x = ele.x + (upRouteNode[index + 1].x - ele.x) / 2 - smallOffestX
            }
          }
          vehicleNode.push({
            id: item.vehicleId,
            x: x,
            y: y,
            shape: 'car_vue_node',
            data: {
              nums: 0,
              isPlateNo,
              isSmall,
              ...item
            }
          })
        }
      })
    } else if (downRouteNode.length) {

      // 下行车辆
      downRouteNode.forEach((ele,index) => {

        if (routeId == ele.id) {
          let x, smallOffestX;
          smallOffestX = !isSmall ? 20 : 0;
          if (item.onStation == true) {
            x = ele.x - smallOffestX
          } else {
            x = ele.x - (ele.x - downRouteNode[index - 1].x) / 2 - smallOffestX
          }
          vehicleNode.push({
            id: item.vehicleId,
            x: x,
            y: ele.y + 20,
            shape: 'car_vue_node',
            data: {
              nums: 0,
              isPlateNo,
              isSmall,
              ...item
            }
          })
        }
      })
    }
  })
  return vehicleNode
}

/**
 * 传入上下行线路，返回上下行站点信息数据(合并线路用)
 * @param {Array} Route [合并线路后端原始数据]
 * */
export const initMergeRouteData = (Route, containerWidth, containerHeight) => {

  // 筛选出主从线路
  let upMainLine = []
  let downMainLine = []
  let upSubordinateLine = []
  let downSubordinateLine = []
  let downSubordinateLineArr = []
  let upSubordinateLineArr = []
  let defaultPostition_y = containerHeight / 2
  Route.forEach(item => {
    if (item.isMainLine == 1) {
      upMainLine.push(...item.upStationList)
      downMainLine.push(...item.downStationList)
    } else {
      upSubordinateLine.push(item.upStationList)
      downSubordinateLine.push(item.downStationList)
    }
  });

  // 计算主线站点
  const {upArr, downArr} = initRouteData(upMainLine, downMainLine, containerWidth, containerHeight)

  // 根据主线站点返回主线站间线
  const {upLineArr,  downLineArr} = initEdgeData(upArr, downArr)

  // 从线
  let upSubordinateArr = []
  let downSubordinateArr = []

  upSubordinateLine.forEach((lineItem, outsideIndex) => {
    // 记录上行从线坐标值
    let upSubordinate_x = 0
    let upSubordinate_y = 0
    let upFirstDiff = false
    upSubordinateArr.push([])
    lineItem.forEach((item, index) => {
      let lastItem = lineItem[index == 0 ? index : index - 1]

      // 首次不同点
      if (item.isMerge == 2 && !upFirstDiff) {
        upFirstDiff = true
        upArr.forEach((ele) => {
          if (ele.id == lastItem.stationId + lastItem.direction) {
            upSubordinate_x = ele.x + 80
            upSubordinate_y = ele.y - (80 * (outsideIndex + 1))
            upSubordinateArr[outsideIndex].push({
              id: item.stationId + item.direction,
              x: upSubordinate_x,
              y: upSubordinate_y,

              // 上行从线站点在上方
              shape: 'up-big-custom-circle',
              attrs: {
                label: {
                  x: -30,
                  y: 0,
                  text: item.stationName,
                },
              },
              data: {
                ...item
              },
            })

            // 画转折位置实线
            upSubordinateLineArr.push({
              source: {
                x: ele.x + 15,
                y: upSubordinate_y + 6
              },
              target: item.stationId + item.direction,
              markup: [{
                  tagName: 'path',
                  selector: 'stroke',
                },
                {
                  tagName: 'path',
                  selector: 'fill',
                },
              ],
              connector: {
                name: 'rounded'
              },
              attrs: {
                fill: {
                  connection: true,
                  fill: 'none',
                },
                stroke: {
                  fill: 'none',
                  stroke: '#4BD17A',
                  strokeWidth: 4,
                  connection: true,
                  strokeLinecap: 'round',
                },
              },
            })

            // 画转折位置虚线线
            upSubordinateLineArr.push({
              source: ele.id,
              target: {
                x: ele.x + 10,
                y: upSubordinate_y + 10
              },
              markup: [{
                  tagName: 'path',
                  selector: 'stroke',
                },

                {
                  tagName: 'path',
                  selector: 'fill',
                },
                {
                  tagName: 'rect',
                  selector: 'sign',
                },
                {
                  tagName: 'text',
                  selector: 'signText',
                },

              ],
              attrs: {
                fill: {
                  connection: true,
                  fill: 'none',
                },
                stroke: {
                  fill: 'none',
                  strokeDasharray: 10,
                  targetMarker: 'classic',
                  stroke: '#4BD17A',
                  strokeWidth: 4,
                  connection: true,
                  strokeLinecap: 'round',
                },
                sign: {
                  x: 10,
                  y: -10,
                  width: 50,
                  height: 20,
                  stroke: '#237804',
                  fill: '#fff',
                  atConnectionLength: 30,
                  strokeWidth: 1,
                },
                signText: {
                  x: 180,
                  y: -(ele.x + 8),
                  atConnectionLength: 30,
                  stroke: '#4bd17a',
                  textAnchor: 'middle',
                  textVerticalAnchor: 'middle',
                  text: '888路',
                },
              },
            })
          }
        })

      } else {

        // 经过第一个不同点后进行后续加点.
        if (upFirstDiff) {
          upSubordinate_x = upSubordinate_x + 120
          upSubordinateArr[outsideIndex].push({
            id: item.stationId + item.direction + '34',
            x: upSubordinate_x,
            y: upSubordinate_y,

            // 上行从线站点在上方
            shape: 'up-big-custom-circle',
            attrs: {
              label: {
                x: -30,
                y: 0,
                text: item.stationName,
              },
            },
            data: {
              ...item
            },
          })
        }
      }
    })
  })

  // 下行合并线
  downSubordinateLine.forEach((lineItem, outsideIndex) => {
    let downSubordinate_x = 0
    let downSubordinate_y = 0
    let downFirstDiff = false
    downSubordinateArr.push([])
    lineItem.forEach((item, index) => {
      let lastItem = lineItem[index == 0 ? index : index - 1]

      // 首次不同点
      if (item.isMerge == 2 && !downFirstDiff) {
        downFirstDiff = true
        downArr.forEach((ele) => {
          if (ele.id == lastItem.stationId + lastItem.direction) {
            downSubordinate_x = ele.x + 80
            downSubordinate_y = ele.y + (80 * (outsideIndex + 1))
            downSubordinateArr[outsideIndex].push({
              id: item.stationId + item.direction + '23',
              x: downSubordinate_x,
              y: downSubordinate_y,

              // 下行站点线在下方
              shape: 'down-big-custom-circle',
              attrs: {
                label: {
                  x: 20,
                  y: -10,
                  text: item.stationName,
                },
              },
              data: {
                ...item
              },
            })
            downSubordinateLineArr.push({
              source: {
                x: ele.x + 10,
                y: downSubordinate_y + 10
              },
              target: item.stationId + item.direction + '23',
              markup: [{
                  tagName: 'path',
                  selector: 'stroke',
                },
                {
                  tagName: 'path',
                  selector: 'fill',
                },
              ],
              connector: {
                name: 'rounded'
              },
              attrs: {
                fill: {
                  connection: true,
                  fill: 'none',
                },
                stroke: {
                  fill: 'none',
                  stroke: '#668ff5',
                  strokeWidth: 4,
                  connection: true,
                  strokeLinecap: 'round',
                },
              },
            })

            // 画转折位置实线
            downSubordinateLineArr.push({
              source: ele.id,
              target: {
                x: ele.x + 10,
                y: downSubordinate_y + 10
              },
              markup: [{
                  tagName: 'path',
                  selector: 'stroke',
                },

                {
                  tagName: 'path',
                  selector: 'fill',
                },
                {
                  tagName: 'rect',
                  selector: 'sign',
                },
                {
                  tagName: 'text',
                  selector: 'signText',
                },

              ],
              attrs: {
                fill: {
                  connection: true,
                  fill: 'none',
                },
                stroke: {
                  fill: 'none',
                  strokeDasharray: 10,
                  targetMarker: 'classic',
                  stroke: '#668ff5',
                  strokeWidth: 4,
                  connection: true,
                  strokeLinecap: 'round',
                },
                sign: {
                  x: 0,
                  y: -10,
                  width: 50,
                  height: 20,
                  stroke: '#668ff5',
                  fill: '#fff',
                  atConnectionLength: 30,
                  strokeWidth: 1,
                },
                signText: {
                  x: 420,
                  y: -ele.x - 8,
                  atConnectionLength: 30,
                  stroke: '#668ff5',
                  textAnchor: 'middle',
                  textVerticalAnchor: 'middle',
                  text: '108路',
                },
              },
            })
          }
        })
      } else {

        // 经过第一个不同点后进行后续加点.
        if (downFirstDiff) {
          downSubordinate_x = downSubordinate_x + 150
          downSubordinateArr[outsideIndex].push({
            id: item.stationId + item.direction + '34',
            x: downSubordinate_x,
            y: downSubordinate_y,

            // 下行站点线在下方
            shape: 'down-big-custom-circle',
            attrs: {
              label: {
                x: 50,
                y: -10,
                text: item.stationName,
              },
            },
            data: {
              ...item
            },
          })
        }
      }
    })
  })
  upSubordinateArr.forEach((item, index) => {
    const SubordinateArr = initEdgeData(item, downSubordinateArr[index])
    upSubordinateLineArr.push(...SubordinateArr.upLineArr)
    downSubordinateLineArr.push(...SubordinateArr.downLineArr)
  })
  return {
    upSubordinateArr,
    downSubordinateArr,
    upArr,
    upLineArr,
    downArr,
    downLineArr,
    downSubordinateLineArr,
    upSubordinateLineArr
  }
}

/**
 * 传入车辆数据+合并线路信息,返回合并从线车辆位置信息
 * @param {Array} vehicleList [当前线路车辆信息]
 * @param {Array} MergeRoute [当前线路车辆信息]
 */
export const initMergeCarData = () => {
  // todo
}

/**
 * 车辆移动
 * @param {*} graph 
 * @param {*} result 
 * @param {*} isSmall 
 * @param {*} routeType 
 * @returns 
 */
export const moveCar = (graph, result, isPlateNo = false, isSmall = false) => {
  // todo
  let carNode = graph.getCellById(result.vehicleId)
  let currStationId = result.stationId + '-' + result.direction + '-' + result.stationOrder
  let lastStationId = result.endStationId + '-' + result.direction + '-' + result.endStationOrder
  if (currStationId == lastStationId) {
    carNode ? graph.removeNode(carNode):'';
    return true;
  }
  let currStationObj = graph.getCellById(currStationId)
  let {
    x: curStationX,
    y: curStationY
  } = currStationObj.position()
  // console.log('currStationObj', currStationObj.getData(), curStationX, curStationY);
  let smallOffestX = !isSmall ? 20 : 0;
  let carX, carY;
  let nextStationId = result.nextStationId + '-' + result.direction + '-' + result.nextStationOrder
  let nextStationObj = graph.getCellById(nextStationId)
  let {
    x: nextStationX,
    y: nextStationY
  } = nextStationObj.position()
  let carPositionX = 0,
    carPositionY = 0;
  if (carNode != null) {
    let carPosition = carNode.position();
    carPositionX = carPosition.x
    carPositionY = carPosition.y
  }
  let currStationInfo = currStationObj.getData();
  if (currStationInfo.hasOwnProperty('middleNum')) {
    //说明是环线线路
    let direction = 1;
    if (result.stationOrder < currStationInfo.middleNum) {
      carY = curStationY - 30
    }else if (result.stationOrder == currStationInfo.middleNum) {
      if (result.onStation == true) {
        carY = curStationY - 30
      } else {
        carY = nextStationY + 20
        direction = 2;
      }
    } else {
      carY = curStationY + 20
      direction = 2;
    }
    if (result.onStation == true) {
      carX = curStationX - smallOffestX
    } else if (result.onStation == false && result.stationOrder != result.endStationOrder) {
      if (direction == 1) {
        //计算左到右
        carX = curStationX  + (nextStationX - curStationX) / 2 - smallOffestX
      } else {
        //计算右到左
        carX = curStationX  - (curStationX - nextStationX) / 2 - smallOffestX
        if (result.stationOrder ==  currStationInfo.middleNum) {
          carX = curStationX + 20
        }
      }
    }
  } else {
    if (result.onStation == true) {
      carX = curStationX;
      carY = result.direction == 1 ? curStationY - 30 : curStationY + 20;
    } else {
      let x;
      if (result.direction == 1) {
        carY = curStationY - 30;
        //计算左到右
        x = curStationX + (nextStationX - curStationX) / 2 - smallOffestX
      } else {
        //计算右到左
        x = curStationX - (curStationX - nextStationX) / 2 - smallOffestX
        carY = curStationY + 20;
      }
      carX = x;

    }
  }

  if (carNode != null) {
    let data = carNode.getData()
    
    carNode.setData(Object.assign(data,{ ...result, isPlateNo, isSmall: isSmall.value }))
    carNode.position(carX, carY);
  } else {
    let node = {
      id: result.vehicleId,
      x: carX,
      y: carY,
      shape: 'car_vue_node',
      data: {
        nums: 0,
        isPlateNo,
        isSmall,
        ...result
      }
    }
    graph.addNode(node)
  }
  return true;
}
